package me.phelps.webrtctest;

import android.media.MediaCodec;
import android.media.MediaFormat;

import java.io.IOException;

/**
 * Created by User on 2016/11/4.
 */

public class AudioCodecHelper implements AudioConstants{

    public static short[] genShorts(){
        return new short[BYTES_PER_BUF/2];
    }

    public static byte[] genBytes(){
        return new byte[BYTES_PER_BUF];
    }

    public static MediaFormat genFormatAAC(){
        MediaFormat format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC,SAMPLE_RATE,CHANNEL);
        format.setInteger(MediaFormat.KEY_BIT_RATE,SAMPLE_RATE*BYTES_PER_FRAME*CHANNEL);
//        format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE,BYTES_PER_BUF);//最大输入，设置为每个缓冲区就编码一次
        return format;
    }

    public static MediaCodec createEncoder(MediaFormat format){
        try {
            MediaCodec encoder = MediaCodec.createEncoderByType(format.getString(MediaFormat.KEY_MIME));
            encoder.configure(format,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
            return encoder;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static MediaCodec createDecoder(MediaFormat format){
        try {
            MediaCodec decoder = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
            return decoder;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void releaseCodec(MediaCodec codec){
        codec.stop();
        codec.release();
        codec=null;
    }
}
